//
//  DrawPad.m
//  Touch
//
//  Created by cocoazxj@163.com on 15/4/20.
//  Copyright (c) 2015年 handcool. All rights reserved.
//

#import "DrawPad.h"

@interface DrawPad()
@property (nonatomic, strong) NSMutableArray *pathArray;
@end

@implementation DrawPad

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (NSMutableArray *)pathArray
{
    if(!_pathArray)
    {
        _pathArray = [NSMutableArray array];
    }
    return _pathArray;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint startPoint = [touch locationInView:self];
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:startPoint];
    [self.pathArray addObject:path];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint movePoint = [touch locationInView:self];
    UIBezierPath *path = [self.pathArray lastObject];
    [path addLineToPoint:movePoint];
    [self setNeedsDisplay];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint movePoint = [touch locationInView:self];
    UIBezierPath *path = [self.pathArray lastObject];
    [path addLineToPoint:movePoint];
}

- (void)drawRect:(CGRect)rect
{
    [[UIColor blackColor] set];
    for (int i = 0; i < self.pathArray.count; i++)
    {
        UIBezierPath *path = self.pathArray[i];
        [path setLineWidth:10];
        [path stroke];
    }
}

- (void)clear
{
    [self.pathArray removeAllObjects];
    [self setNeedsDisplay];
}
- (void)undo
{
    [self.pathArray removeLastObject];
    [self setNeedsDisplay];
}
- (void)save
{
    UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0);
    [[UIColor blackColor] set];
    for (int i = 0; i < self.pathArray.count; i++)
    {
        UIBezierPath *path = self.pathArray[i];
        [path setLineWidth:10];
        [path stroke];
    }
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError: contextInfo:), NULL);
    
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if(error)
    {
        NSLog(@"失败！");
    }
    else
    {
        NSLog(@"成功！");
    }
}

@end
